package org.hales.security;

import org.hales.common.ServerResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.hales.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component("loginFailureHandler")
public class LoginFailureHandler implements AuthenticationFailureHandler{
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private UserService userService;

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        logger.info("登录失败");
        String username = httpServletRequest.getParameter("username");

        ServerResponse serverResponse =  userService.LoginSecurityFail(username);
        httpServletResponse.setStatus(HttpStatus.OK.value());
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        if (serverResponse != null) {
            httpServletResponse.getWriter().write(objectMapper.writeValueAsString(serverResponse)); // 使用返回的ServerResponse
        } else {
            // 如果LoginSecurityFail返回null，可能需要处理这种情况，比如返回默认错误信息
            httpServletResponse.getWriter().write(objectMapper.writeValueAsString(ServerResponse.createByErrorMessage("登录失败：" + e.getMessage())));
        }
    }
}



